package com.google.wave.poppy.model;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.wave.api.Wavelet;

/**
 * Interface to store and retrieve external email participants for a wave.
 * 
 * @author prathapnirmal
 *
 */
public class EmailStorage {
	
	/**
	 * Name of the data document to which the email addresses are stored.
	 */
	private static final String EMAIL_PARTICIPANTS_DOC = "email_participants";
	
	/**
	 * Email addreses key for the JSON object.
	 */
	private static final String EMAIL_KEY = "emails";
	
	/**
	 * Wavelet for the email document.
	 */
	private Wavelet wavelet;
	
	/**
	 * Constructor.
	 * 
	 * @param wavelet wavelet to which the email addresses should be stored or 
	 * retrieved from.
	 * 
	 */
	public EmailStorage(Wavelet wavelet) {
		this.wavelet = wavelet;
		
		// Add the data document if it doesn't exist already.
		if (!wavelet.hasDataDocument(EMAIL_PARTICIPANTS_DOC)) {
			try {
				JSONObject emailsJSON = new JSONObject().put(EMAIL_KEY,
						new JSONArray());
				wavelet.setDataDocument(EMAIL_PARTICIPANTS_DOC, 
						emailsJSON.toString());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
		
	/**
	 * Adds a new email participant to the wave.
	 * 
	 * @param emailAddress
	 */
	public void addEmailParticipant(String emailAddress) {
		String emailData = this.wavelet.getDataDocument(
				EMAIL_PARTICIPANTS_DOC);
		try {
			JSONObject emailsJSON = new JSONObject(emailData);
			JSONArray emails = emailsJSON.getJSONArray(EMAIL_KEY);
			
			// avoid duplicates.
			for (int i = 0; i < emails.length(); i++) {
				String e = emails.getString(i);
				if (emailAddress.equals(e)) {
					return;
				}
			}
			
			emails.put(emailAddress);
			this.wavelet.setDataDocument(EMAIL_PARTICIPANTS_DOC,
					emailsJSON.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Gets the list of email participants for the current wavelet.
	 * 
	 * @return the list of email participants for the current wavelet.
	 * 
	 */
	public JSONArray getEmailParticipants() {
		String emailData = this.wavelet.getDataDocument(
				EMAIL_PARTICIPANTS_DOC);
		JSONArray emails = new JSONArray();
		try {
			JSONObject emailsJSON = new JSONObject(emailData);
			emails = emailsJSON.getJSONArray(EMAIL_KEY);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return emails;
	}

}
